package com.baidu.sggc.service;

import com.baidu.sggc.data.req.FileInfoCreateReq;
import com.baidu.sggc.data.req.FileInfoDelReq;
import com.baidu.sggc.data.req.FileInfoListReq;
import com.baidu.sggc.entity.FileInfo;
import com.baidu.sggc.entity.UserContext;
import com.baidu.sggc.mapper.FileInfoMapper;
import com.baidu.sggc.entity.vo.FileInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 文件信息表 服务实现类
 * </p>
 *
 * @author xiongziming
 * @since 2025-02-18
 */
@Service
public class FileInfoService {
    @Autowired
    private FileInfoMapper fileInfoMapper;

    public Long createFileInfo(FileInfoCreateReq req) {
        FileInfo fileInfo = new FileInfo();
        BeanUtils.copyProperties(req, fileInfo);

        // 从当前线程上下文中取用户信息
        String userId = UserContext.getUserId();
        String userName = UserContext.getUserName();

        // 设置创建人信息
        fileInfo.setCreateId(userId);
        fileInfo.setCreateName(userName != null ? userName : "系统账号");

        // 插入数据库
        int rows = fileInfoMapper.insert(fileInfo);
        if (rows > 0) {
            return fileInfo.getId(); // 主键 ID 会被 MyBatis 自动回填
        }
        return null;
    }

    public boolean deleteFileInfoById(FileInfoDelReq req) {
        boolean b;
        try {
            FileInfo fileInfo = new FileInfo();
            BeanUtils.copyProperties(req, fileInfo);
            b = fileInfoMapper.deleteById(fileInfo) > 0;
        } catch (Exception e) {
            throw new RuntimeException("Delete failed: ", e);
        }
        return b;
    }


    public List<FileInfoVo> getFileInfoList(FileInfoListReq req) {
        List<FileInfoVo> fileInfoList;
        try {
            fileInfoList = fileInfoMapper.getFileInfoList(req);
        } catch (Exception e) {
            throw new RuntimeException("Select failed: ", e);
        }
        return fileInfoList;
    }

    public FileInfoVo getFileInfoById(Long id) {
        FileInfoVo fileInfoVo = null;
        try {
            LambdaQueryWrapper<FileInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FileInfo::getId, id)
                    .eq(FileInfo::getIsDel, 0);
            FileInfo fileInfo = fileInfoMapper.selectOne(queryWrapper);
            if (fileInfo != null) {
                fileInfoVo = new FileInfoVo();
                BeanUtils.copyProperties(fileInfo, fileInfoVo);
            }
        } catch (Exception e) {
            throw new RuntimeException("Select failed: ", e);
        }
        return fileInfoVo;
    }
}
